package io.kimmking.rpcfx.server;
  
import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;  
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;  
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;  
import static io.netty.handler.codec.http.HttpResponseStatus.OK;  
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import com.alibaba.fastjson.JSON;
import io.kimmking.rpcfx.api.RpcfxRequest;
import io.kimmking.rpcfx.api.RpcfxResponse;
import io.kimmking.rpcfx.tcp.CustomTcpMessage;
import io.netty.util.CharsetUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;  
  
import io.netty.buffer.ByteBuf;  
import io.netty.buffer.Unpooled;  
import io.netty.channel.ChannelHandlerContext;  
import io.netty.channel.ChannelInboundHandlerAdapter;  
import io.netty.handler.codec.http.DefaultFullHttpResponse;  
import io.netty.handler.codec.http.FullHttpResponse;  
import io.netty.handler.codec.http.HttpContent;  
import io.netty.handler.codec.http.HttpHeaders;  
import io.netty.handler.codec.http.HttpHeaders.Values;  
import io.netty.handler.codec.http.HttpRequest;  
  
public class HttpServerInboundHandler extends ChannelInboundHandlerAdapter {  
  
    private static Log log = LogFactory.getLog(HttpServerInboundHandler.class);  
  
    private HttpRequest request;
    RpcfxInvoker invoker;
    public HttpServerInboundHandler(RpcfxInvoker invoker) {
        this.invoker = invoker;
    }

    @Override  
    public void channelRead(ChannelHandlerContext ctx, Object msg)  
            throws Exception {
        if (msg instanceof CustomTcpMessage) {
            CustomTcpMessage rec = (CustomTcpMessage) msg;
            String body = rec.getBody();
            String header = rec.getHeader();
            System.out.println("rec header:"+header);
            System.out.println("rec body:"+body);


            RpcfxRequest req = JSON.parseObject(body,RpcfxRequest.class);
            //RpcfxRequest req = JSON.parseObject(body,RpcfxRequest.class);
            RpcfxResponse rep = invoker.invoke(req);
            String res = JSON.toJSONString(rep);
            CustomTcpMessage response = new CustomTcpMessage();
            //服务端将header原路返回
            response.setHeader(header);
            response.setBody(res);
            ctx.write(response);  
            ctx.flush();  
        }  
    }  
  
    @Override  
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {  
        ctx.flush();  
    }  
  
    @Override  
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {  
        log.error(cause.getMessage());  
        ctx.close();  
    }  
  
} 